package com.collectplus.express.city;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.collectplus.express.BaseActivity2;
import com.collectplus.express.R;
import com.collectplus.express.logic.AppHttp;
import com.collectplus.express.logic.AppResult;
import com.collectplus.express.logic.JSON;
import com.collectplus.express.logic.MsgID;
import com.collectplus.express.model.CalculateProvinceBean;
import com.collectplus.express.model.ProvinceBean;
import com.collectplus.express.model.ReceiverBean;
import com.shouhuobao.bhi.receiver.ReceiverHistoryFragment;

import java.util.ArrayList;
import java.util.List;

import droid.frame.activity.base.FrameBaseActivity;
import droid.frame.ui.dialog.AppLoading;
import droid.frame.utils.android.Alert;

/**
 * 选择省市县
 * 去掉 新疆、西藏、青海、海南、贵州<br>
 * 记得修改{@link ReceiverHistoryFragment#regex}
 *
 * @author coffee<br>
 *         2016-12-19下午2:49:25
 */
public class ChooseAreaActivity extends FrameBaseActivity implements OnClickListener {
    //    private final String[][] ARR_AG = {{"安徽", "340000"}, {"北京", "110000"}, {"重庆", "500000"}, {"福建", "350000"}, {"甘肃", "620000"}, {"广东", "440000"}, {"广西", "450000"}};
//    private final String[][] ARR_HK = {{"河北", "130000"}, {"河南", "410000"}, {"黑龙江", "230000"}, {"湖北", "420000"}, {"湖南", "430000"}, {"吉林", "220000"}, {"江苏", "320000"}, {"江西", "360000"}};
//    private final String[][] ARR_LS = {{"辽宁", "210000"}, {"内蒙", "150000"}, {"宁夏", "640000"}, {"山东", "370000"}, {"山西", "140000"}, {"陕西", "610000"}, {"上海", "310000"}, {"四川", "510000"}};
//    private final String[][] ARR_TZ = {{"天津", "120000"}, {"云南", "530000"}, {"浙江", "330000"}};
    private List<ProvinceBean.Province> ARR_AG = null;
    private List<ProvinceBean.Province> ARR_HK = null;
    private List<ProvinceBean.Province> ARR_LS = null;
    private List<ProvinceBean.Province> ARR_TZ = null;

    private LinearLayout mAllLayout;

    private LinearLayout mProvinceLayout, mCityLayout, mAreaLayout;
    private ImageView mProvinceArrow, mCityArrow, mAreaArrow;// 省市区
    private LinearLayout mProvinceGridLayout;
    private GridView mGridViewAG, mGridViewHK, mGridViewLS, mGridViewTZ, // 拼音
            mGridViewCity, mGridViewArea;// 城市、市区
    private TextView mAddressTv1, mAddressTv2, mAddressTv3;

//    private CityUtils mCityUtils;

    private AreaAdapter mCityAdapter;
    private AreaAdapter mAreaAdapter;
    private AppLoading loading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setStatusBarColor(0);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.city_choose);
        super.findViewById();
        mAllLayout = (LinearLayout) findViewById(R.id.choose_area_all_layout);
        mAllLayout.setOnClickListener(this);
        mAddressTv1 = (TextView) findViewById(R.id.choose_area_lable1);
        mAddressTv2 = (TextView) findViewById(R.id.choose_area_lable2);
        mAddressTv3 = (TextView) findViewById(R.id.choose_area_lable3);
        mProvinceLayout = (LinearLayout) findViewById(R.id.choose_province_layout);
        mProvinceLayout.setOnClickListener(this);
        mProvinceArrow = (ImageView) findViewById(R.id.choose_province_arrow);
        mCityLayout = (LinearLayout) findViewById(R.id.choose_city_layout);
        mCityLayout.setOnClickListener(this);
        mCityArrow = (ImageView) findViewById(R.id.choose_city_arrow);
        mAreaLayout = (LinearLayout) findViewById(R.id.choose_area_layout);
        mAreaLayout.setOnClickListener(this);
        mAreaArrow = (ImageView) findViewById(R.id.choose_area_arrow);
        mProvinceGridLayout = (LinearLayout) findViewById(R.id.choose_province_gridview_layout);

        mGridViewAG = (GridView) findViewById(R.id.choose_area_gridview_ag);
        mGridViewAG.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ProvinceBean.Province bean = (ProvinceBean.Province) mGridViewAG.getAdapter().getItem(position);
                if (bean != null) {
//                    mCityUtils.initCities(ARR_AG[position][1]);
                    showLoadingDialog(null);
                    AppHttp.getInstance().getProvinceCityData(1, bean.getId() + "");
                    closeProvinceLayout();
                    setProvinceTv(bean.getName(), bean.getId() + "");
                }
            }
        });
        mGridViewHK = (GridView) findViewById(R.id.choose_area_gridview_hk);
        mGridViewHK.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                mCityUtils.initCities(ARR_HK[position][1]);
//                closeProvinceLayout();
//                setProvinceTv(ARR_HK[position][0], ARR_HK[position][1]);
                ProvinceBean.Province bean = (ProvinceBean.Province) mGridViewHK.getAdapter().getItem(position);
                if (bean != null) {
                    showLoadingDialog(null);
                    AppHttp.getInstance().getProvinceCityData(1, bean.getId() + "");
                    closeProvinceLayout();
                    setProvinceTv(bean.getName(), bean.getId() + "");
                }
            }
        });
        mGridViewLS = (GridView) findViewById(R.id.choose_area_gridview_ls);
        mGridViewLS.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                mCityUtils.initCities(ARR_LS[position][1]);
//                closeProvinceLayout();
//                setProvinceTv(ARR_LS[position][0], ARR_LS[position][1]);
                ProvinceBean.Province bean = (ProvinceBean.Province) mGridViewLS.getAdapter().getItem(position);
                if (bean != null) {
                    showLoadingDialog(null);
                    AppHttp.getInstance().getProvinceCityData(1, bean.getId() + "");
                    closeProvinceLayout();
                    setProvinceTv(bean.getName(), bean.getId() + "");
                }
            }
        });
        mGridViewTZ = (GridView) findViewById(R.id.choose_area_gridview_tz);
        mGridViewTZ.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                mCityUtils.initCities(ARR_TZ[position][1]);
//                closeProvinceLayout();
//                setProvinceTv(ARR_TZ[position][0], ARR_TZ[position][1]);
                ProvinceBean.Province bean = (ProvinceBean.Province) mGridViewTZ.getAdapter().getItem(position);
                if (bean != null) {
                    showLoadingDialog(null);
                    AppHttp.getInstance().getProvinceCityData(1, bean.getId() + "");
                    closeProvinceLayout();
                    setProvinceTv(bean.getName(), bean.getId() + "");
                }
            }
        });
        mGridViewCity = (GridView) findViewById(R.id.choose_area_gridview_city);
        mGridViewCity.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                closeCityLayout();
//                mCityUtils.initDistricts(mCityAdapter.mArr.get(position).getId());
                ProvinceBean.Province bean = (ProvinceBean.Province) mGridViewCity.getAdapter().getItem(position);
                if (bean != null) {
                    showLoadingDialog(null);
                    AppHttp.getInstance().getProvinceCityData(2, bean.getId() + "");
                }
                setCityTv(position);
            }
        });
        mGridViewArea = (GridView) findViewById(R.id.choose_area_gridview_aera);
        mGridViewArea.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                closeAreaLayout();
                mAddressTv3.setText(mAreaAdapter.mArr.get(position).getName());
                mAddressTv3.setTag(mAreaAdapter.mArr.get(position).getId());
                //
                Intent data = new Intent();
                ReceiverBean receiver = new ReceiverBean();
                receiver.setProvince(mAddressTv1.getText().toString());
                receiver.setCity(mAddressTv2.getText().toString());
                receiver.setDistrict(mAddressTv3.getText().toString());
                receiver.setProvinceId(mAddressTv1.getTag().toString());
                receiver.setCityId(mAddressTv2.getTag().toString());
                receiver.setDistrictId(mAddressTv3.getTag().toString());
                data.putExtra("item", receiver);
                setResult(Activity.RESULT_OK, data);
                finish();
            }
        });
        showLoadingDialog(null);
        AppHttp.getInstance().getProvinceCityData(0, "1");
    }

    private void setProvinceTv(String province, String id) {
        mAddressTv1.setText(province);
        mAddressTv1.setTag(id);
        mAddressTv2.setText(null);
        mAddressTv3.setText(null);
    }

    private void setCityTv(int position) {
        mAddressTv2.setText(mCityAdapter.mArr.get(position).getName());
        mAddressTv2.setTag(mCityAdapter.mArr.get(position).getId());
        mAddressTv3.setText(null);
    }

//    private Handler mCityHandler = new Handler(new Handler.Callback() {
//        @SuppressWarnings("unchecked")
//        @Override
//        public boolean handleMessage(Message msg) {
//            switch (msg.what) {
//                case 2:
//                    if (mCityAdapter == null) {
//                        mCityAdapter = new AreaAdapter(ChooseAreaActivity.this, (ArrayList<MyRegion>) msg.obj);
//                        mGridViewCity.setAdapter(mCityAdapter);
//                    } else
//                        mCityAdapter.notifyDataSetChanged((ArrayList<MyRegion>) msg.obj);
//                    showCityLayout();
//                    break;
//                case 3:
//                    if (mAreaAdapter == null) {
//                        mAreaAdapter = new AreaAdapter(ChooseAreaActivity.this, (ArrayList<MyRegion>) msg.obj);
//                        mGridViewArea.setAdapter(mAreaAdapter);
//                    } else
//                        mAreaAdapter.notifyDataSetChanged((ArrayList<MyRegion>) msg.obj);
//                    showAreaLayout();
//                    break;
//            }
//            return false;
//        }
//    });

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.choose_province_layout:// 省
                showProvinceLayout();
                closeAreaLayout();
                closeCityLayout();
                break;
            case R.id.choose_city_layout:// 市
                if (TextUtils.isEmpty(mAddressTv1.getText().toString())) {
                    Alert.toast("请选择省份");
                } else {
                    closeProvinceLayout();
                    closeAreaLayout();
                    showCityLayout();
                }
                break;
            case R.id.choose_area_layout:// 区
                if (TextUtils.isEmpty(mAddressTv2.getText().toString())) {
                    Alert.toast("请选择城市");
                } else {
                    closeProvinceLayout();
                    closeCityLayout();
                    showAreaLayout();
                }
                break;
            case R.id.choose_area_all_layout:
                finish();
                break;
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            //获取省
            case MsgID.self_province_city:
                cancelLoadingDialog();
                final AppResult<ProvinceBean> result = JSON.parseList(msg.obj, ProvinceBean.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (result.isSuccess()) {
                            List<ProvinceBean> beans = result.getResultList();
                            for (ProvinceBean bean : beans) {
                                if ("A-G".equals(bean.getName())) {
                                    ARR_AG = bean.getProvinces();
                                } else if ("H-K".equals(bean.getName())) {
                                    ARR_HK = bean.getProvinces();
                                } else if ("L-S".equals(bean.getName())) {
                                    ARR_LS = bean.getProvinces();
                                } else if ("T-Z".equals(bean.getName())) {
                                    ARR_TZ = bean.getProvinces();
                                }
                            }
                            mGridViewAG.setAdapter(new CityAdapter(getContext(), ARR_AG));
                            mGridViewHK.setAdapter(new CityAdapter(getContext(), ARR_HK));
                            mGridViewLS.setAdapter(new CityAdapter(getContext(), ARR_LS));
                            mGridViewTZ.setAdapter(new CityAdapter(getContext(), ARR_TZ));
                        } else {
                            showToast(result.getMessage());
                        }
                    }
                });
                return false;
            //获取市
            case MsgID.self_province_city + 1:
                cancelLoadingDialog();
                final AppResult<ProvinceBean> result1 = JSON.parseList(msg.obj, ProvinceBean.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (result1.isSuccess()) {
                            List<ProvinceBean> cityList = result1.getResultList();
                            if (cityList == null || cityList.size() == 0) {
                                return;
                            }
                            if (mCityAdapter == null) {
                                mCityAdapter = new AreaAdapter(getContext(), (ArrayList<ProvinceBean.Province>) cityList.get(0).getProvinces());
                                mGridViewCity.setAdapter(mCityAdapter);
                            } else
                                mCityAdapter.notifyDataSetChanged((ArrayList<ProvinceBean.Province>) cityList.get(0).getProvinces());
                            if (cityList.get(0).getProvinces().size() == 1) {
                                setCityTv(0);
                                showLoadingDialog(null);
                                AppHttp.getInstance().getProvinceCityData(2, cityList.get(0).getProvinces().get(0).getId() + "");
                            } else {
                                showCityLayout();
                            }
                        } else {
                            showToast(result1.getMessage());
                        }
                    }
                });
                return false;
            //获取县
            case MsgID.self_province_city + 2:
                cancelLoadingDialog();
                final AppResult<ProvinceBean> result2 = JSON.parseList(msg.obj, ProvinceBean.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (result2.isSuccess()) {
                            List<ProvinceBean> areaList = result2.getResultList();
                            if (areaList == null || areaList.size() == 0) {
                                return;
                            }

                            if (mAreaAdapter == null) {
                                mAreaAdapter = new AreaAdapter(getContext(), (ArrayList<ProvinceBean.Province>) areaList.get(0).getProvinces());
                                mGridViewArea.setAdapter(mAreaAdapter);
                            } else
                                mAreaAdapter.notifyDataSetChanged((ArrayList<ProvinceBean.Province>) areaList.get(0).getProvinces());
                            showAreaLayout();
                        } else {
                            showToast(result2.getMessage());
                        }
                    }
                });
                return false;
            default:
                return super.handleMessage(msg);
        }
    }

    private void closeProvinceLayout() {
        mProvinceGridLayout.setVisibility(View.GONE);
        mProvinceArrow.setImageResource(R.drawable.arrow_down_2);
    }

    private void showProvinceLayout() {
        mProvinceGridLayout.setVisibility(View.VISIBLE);
        mProvinceArrow.setImageResource(R.drawable.arrow_up_2);
    }

    private void closeCityLayout() {
        mGridViewCity.setVisibility(View.GONE);
        mCityArrow.setImageResource(R.drawable.arrow_down_2);
    }

    private void showCityLayout() {
        mGridViewCity.setVisibility(View.VISIBLE);
        mCityArrow.setImageResource(R.drawable.arrow_up_2);
        if (mCityAdapter.getCount() == 1) {
            closeCityLayout();
//            mCityUtils.initDistricts(mCityAdapter.mArr.get(0).getId());
            setCityTv(0);
        }
    }

    /**
     * 关于区域
     */
    private void closeAreaLayout() {
        mGridViewArea.setVisibility(View.GONE);
        mAreaArrow.setImageResource(R.drawable.arrow_down_2);
    }

    private void showAreaLayout() {
        mGridViewArea.setVisibility(View.VISIBLE);
        mAreaArrow.setImageResource(R.drawable.arrow_up_2);
    }

    public void showLoadingDialog(final String dialogMessage) {
        getContext().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (loading != null && loading.isShowing()) {
                    loading.setMessage(dialogMessage);
                    return;
                } else {
                    loading = new AppLoading(getContext());
                    loading.setMessage(dialogMessage);
                    loading.show();
                }
            }
        });
    }

    protected void cancelLoadingDialog() {
        getContext().runOnUiThread(new Runnable() {
            public void run() {
                if (loading != null) {
                    loading.dismiss();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        if (loading != null) {
            loading.dismiss();
        }
        super.onDestroy();
    }
}
